﻿using System;
using System.Collections.Generic;

using SBPweb.Communication.Shared.Library;
using SBPweb.Communication.Shared.Library.Contacts;
using SBPweb.Communication.Shared.Library.Conversations;

using SBPweb.Communication.Client.Library.Xmpp.Commands;
using SBPweb.Communication.Client.Library.Xmpp.Contacts;
using SBPweb.Communication.Client.Library.Xmpp.Connections;

namespace SBPweb.Communication.Client.Library.Xmpp.Conversations
{

    public partial class ConversationManager : ConversationManagerBase
    {

        #region Protected fields

        protected ConnectionManager connections;

        #endregion

        #region Constructor logic

        internal ConversationManager(MessengerBase messenger)
            : base(messenger)
        {
        }

        internal ConversationManager(MessengerBase messenger, ConnectionManager connectionManager)
            : base(messenger)
        {
            this.connections = connectionManager;
        }

        #endregion

        #region Property accessors

        internal IContact LocalContact
        {
            get
            {
                return messenger.Contacts.Myself;
            }
        }

        internal ConnectionManager Connections
        {
            get
            {
                return connections;
            }
        }

        public List<IContact> PublicConferences
        {
            get;
            protected set;
        }

        #endregion

        #region Events

        public event EventHandler FindPublicConferencesRequested;

        public event EventHandler FindPublicConferencesReceived;

        #endregion

        #region Methods

        public override void OpenConversationWith(IContact contact)
        {
            CreateConversation(LocalContact, contact);
        }

        public override void OpenConference(IContact conferenceId, List<IContact> members)
        {
            CreateConference(conferenceId, members);
        }

        private Conversation CreateConversation(IContact owner, IContact receipient)
        {
            Conversation conv = new Conversation(owner, receipient);
            conv.Manager = this;
            conversations.Add(receipient, conv);

            OnConversationOpened(this, new ConversationEventArgs(conv));

            return conv;
        }

        private Conference CreateConference(IContact conferenceId, List<IContact> receipients)
        {
            Conference conf = new Conference(LocalContact, conferenceId, receipients);
            conf.Manager = this;
            conversations.Add(conferenceId, conf);
            conf.SendPresence();
            OnConversationOpened(this, new ConversationEventArgs(conf));

            return conf;
        }

        #endregion

    }

}